/*
 * @Descripttion:
 * @version:
 * @Author: ChenXiang
 * @Date: 2021-03-22 16:18:10
 * @LastEditors: ChenXiang
 * @LastEditTime: 2021-09-03 09:37:02
 */

export default {
  /**
   * 对查询关键字中的特殊字符进行编码
   * @param str
   * @returns string
   * @example encodeSearchKey('%123/23=14&66666=99')=> %123/23=14&66666=99
   */
  //  replace(/%40/gi, '@').
  //  replace(/%3A/gi, ':').
  //  replace(/%24/g, '$').
  //  replace(/%2C/gi, ',').
  //  replace(/%20/g, '+').
  //  replace(/%5B/gi, '[').
  //  replace(/%5D/gi, ']');
  encode(str) {
    const encodeArr = [
      {
        code: "+",
        encode: "%2B",
      },
      {
        code: "%",
        encode: "%25",
      },
      {
        code: "?",
        encode: "%3F",
      },
      {
        code: "/",
        encode: "%2F",
      },
      {
        code: "#",
        encode: "%23",
      },
      {
        code: "&",
        encode: "%26",
      },
      {
        code: "=",
        encode: "%3D",
      },
    ];
    return str.replace(/[+%?/#&=]/g, ($, index, str) => {
      for (const k of encodeArr) {
        if (k.code === $) {
          return k.encode;
        }
      }
    });
  },
  unencode(str) {
    return unescape(str)
  },
  // 字符转换，type: 1:首字母大写 2：首字母小写 3：大小写转换 4：全部大写 5：全部小写
  changeCase: (str, type) => {
    type = type || 4;
    switch (type) {
      case 1:
        return str.replace(/\b\w+\b/g, function (word) {
          return (
            word.substring(0, 1).toUpperCase() + word.substring(1).toLowerCase()
          );
        });
      case 2:
        return str.replace(/\b\w+\b/g, function (word) {
          return (
            word.substring(0, 1).toLowerCase() + word.substring(1).toUpperCase()
          );
        });
      case 3:
        return str
          .split("")
          .map(function (word) {
            if (/[a-z]/.test(word)) {
              return word.toUpperCase();
            } else {
              return word.toLowerCase();
            }
          })
          .join("");
      case 4:
        return str.toUpperCase();
      case 5:
        return str.toLowerCase();
      default:
        return str;
    }
  },

  // 自动换行
  autoBr: (str) => {
    return str.replace(/\n/g, "<br>");
  },
  // 判断类型集合
  checkStr: (str, type) => {
    switch (type) {
      case "phone": // 手机号码
        return /^1[3|4|5|6|7|8|9][0-9]{9}$/.test(str);
      case "tel": // 座机
        return /^(0\d{2,3}-\d{7,8})(-\d{1,4})?$/.test(str);
      case "card": // 身份证
        return /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/.test(str);
      case "pwd": // 密码以字母开头，长度在6~18之间，只能包含字母、数字和下划线
        return /^[a-zA-Z]\w{5,17}$/.test(str);
      case "postal": // 邮政编码
        return /[1-9]\d{5}(?!\d)/.test(str);
      case "QQ": // QQ号
        return /^[1-9][0-9]{4,9}$/.test(str);
      case "email": // 邮箱
        return /^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$/.test(str);
      case "money": // 金额(小数点2位)
        return /^\d*(?:\.\d{0,2})?$/.test(str);
      case "URL": // 网址
        return /(http|ftp|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&:/~\+#]*[\w\-\@?^=%&/~\+#])?/.test(
          str
        );
      case "IP": // IP
        return /((?:(?:25[0-5]|2[0-4]\\d|[01]?\\d?\\d)\\.){3}(?:25[0-5]|2[0-4]\\d|[01]?\\d?\\d))/.test(
          str
        );
      case "date": // 日期时间
        return (
          /^(\d{4})\-(\d{2})\-(\d{2}) (\d{2})(?:\:\d{2}|:(\d{2}):(\d{2}))$/.test(
            str
          ) || /^(\d{4})\-(\d{2})\-(\d{2})$/.test(str)
        );
      case "number": // 数字
        return /^[0-9]$/.test(str);
      case "english": // 英文
        return /^[a-zA-Z]+$/.test(str);
      case "chinese": // 中文
        return /^[\\u4E00-\\u9FA5]+$/.test(str);
      case "lower": // 小写
        return /^[a-z]+$/.test(str);
      case "upper": // 大写
        return /^[A-Z]+$/.test(str);
      case "HTML": // HTML标记
        return /<("[^"]*"|'[^']*'|[^'">])*>/.test(str);
      default:
        return true;
    }
  },
  // 去除空格,type: 1-所有空格 2-前后空格 3-前空格 4-后空格
  trim: (str, type: number) => {
    type = type || 1;
    switch (type) {
      case 1:
        return str.replace(/\s+/g, "");
      case 2:
        return str.replace(/(^\s*)|(\s*$)/g, "");
      case 3:
        return str.replace(/(^\s*)/g, "");
      case 4:
        return str.replace(/(\s*$)/g, "");
      default:
        return str;
    }
  },
  // 姓名（不能输入数字以及特殊字符）
  convertName: (val) => {
    if (!val) return val;
    return val
      .replace(/[`!@#$%^&*()_+-<>?:"{},.\/;'[\]]/im, "")
      .replace(/[·！#￥（——）：；“”‘、，|《。》？、【】[\]]/im, "")
      .replace(/[0-9]/g, "");
  },

  /**
   * 字符串出现的次数
   * @param  str 文字
   * @param  char 搜索的字符串
   * @return number
   */

  strCharPosition: (str: string, char: string) => {
    let pos;
    const arr = [];
    pos = str.indexOf(char);
    while (pos > -1) {
      arr.push(pos);
      pos = str.indexOf(char, pos + 1);
    }
    return arr.length;
  },

  /**
   * 查找文字里 所在字符串的下标
   * @param  str  文字
   * @param  char  搜索的字符串
   * @param  num   第几个，输入的值最少为0
   * @return Number
   */

  findStringIndex: function (str: string, cha: string, num: number) {
    let count = num;
    if (num < 0) {
      count = this.strCharPosition(str, cha) - Math.abs(num);
    }

    let x = str.indexOf(cha);
    for (let i = 0; i < count; i++) {
      x = str.indexOf(cha, x + 1);
    }
    return x;
  },
  /*
   * 屏蔽掉emoji表情字符
   * */
  deleteEmoji: function (txt) {
    const reg = new RegExp("%uD[A-Z0-9]{3}", "gi");
    if (!txt) return "";
    txt = escape(txt).toString();
    return unescape(txt.replace(reg, ""));
  },
  /**
   * 判断字符串是否有emoji
   * @param val
   * @returns {boolean}
   */
  hasEmoji: function (val) {
    const str = escape(val).replace(/%/g, "//").toLowerCase().toString();
    const reg = new RegExp("//ud", "gi");
    if (val !== "") {
      if (reg.test(str)) {
        return true;
      } else {
        return false;
      }
    } else {
      return false;
    }
  },
  // 身份证和手机号加密
  encryptIdCard: function (numStr) {
    if (!numStr) return "";
    numStr = numStr + "";
    const reg = /(\d{1})(\d{13}|\d{16})([\d{1}x]$)/gi;
    const regPhone = /(\d{3})\d{4}(\d{4})/g;
    if (numStr.length === 15) {
      numStr = numStr.replace(reg, "$1*************$3");
    }
    if (numStr.length === 18) {
      numStr = numStr.replace(reg, "$1****************$3");
    }
    if (numStr.length === 11) {
      numStr = numStr.replace(regPhone, "$1****$2");
    }
    return numStr;
  },
  // 检测密码强度
  checkPwd: (str) => {
    let Lv = 0;
    if (str.length < 6) {
      return Lv;
    }
    if (/[0-9]/.test(str)) {
      Lv++;
    }
    if (/[a-z]/.test(str)) {
      Lv++;
    }
    if (/[A-Z]/.test(str)) {
      Lv++;
    }
    if (/[\.|-|_]/.test(str)) {
      Lv++;
    }
    return Lv;
  },
  // 16进制颜色转RGBRGBA字符串
  colorToRGB: (val, opa) => {
    const pattern = /^(#?)[a-fA-F0-9]{6}$/; // 16进制颜色值校验规则
    const isOpa = typeof opa === "number"; // 判断是否有设置不透明度

    if (!pattern.test(val)) {
      // 如果值不符合规则返回空字符
      return "";
    }

    const v = val.replace(/#/, ""); // 如果有#号先去除#号
    const rgbArr = [];
    let rgbStr = "";

    for (let i = 0; i < 3; i++) {
      const item = v.substring(i * 2, i * 2 + 2);
      const num = parseInt(item, 16);
      rgbArr.push(num);
    }

    rgbStr = rgbArr.join();
    rgbStr =
      "rgb" +
      (isOpa ? "a" : "") +
      "(" +
      rgbStr +
      (isOpa ? "," + opa : "") +
      ")";
    return rgbStr;
  },
};
